const express = require('express');
const router = express.Router();
const internalService = require('../services/internalService');
const { validateRequest } = require('../middleware/validation');
const logger = require('../utils/logger');

/**
 * @route GET /api/internal/status
 * @desc 获取所有内部服务状态
 * @access Private
 */
router.get('/status', async (req, res) => {
  try {
    logger.info('获取内部服务状态');
    
    const services = internalService.getAllServicesStatus();
    
    res.json({
      success: true,
      data: services,
      timestamp: new Date().toISOString()
    });
  } catch (error) {
    logger.error('获取内部服务状态失败', { error: error.message });
    res.status(500).json({
      success: false,
      error: '获取内部服务状态失败',
      message: error.message
    });
  }
});

/**
 * @route GET /api/internal/status/:serviceName
 * @desc 获取指定内部服务状态
 * @access Private
 */
router.get('/status/:serviceName', async (req, res) => {
  try {
    const { serviceName } = req.params;
    
    logger.info(`获取内部服务状态: ${serviceName}`);
    
    const service = internalService.getServiceStatus(serviceName);
    
    res.json({
      success: true,
      data: service,
      timestamp: new Date().toISOString()
    });
  } catch (error) {
    logger.error(`获取内部服务状态失败: ${req.params.serviceName}`, { error: error.message });
    res.status(500).json({
      success: false,
      error: '获取内部服务状态失败',
      message: error.message
    });
  }
});

/**
 * @route POST /api/internal/task/execute
 * @desc 执行内部任务
 * @access Private
 */
router.post('/task/execute', validateRequest({
  taskType: 'string|required',
  params: 'object|optional'
}), async (req, res) => {
  try {
    const { taskType, params = {} } = req.body;
    
    logger.info(`执行内部任务: ${taskType}`, { params });
    
    const result = await internalService.executeTask(taskType, params);
    
    res.json({
      success: true,
      data: result,
      timestamp: new Date().toISOString()
    });
  } catch (error) {
    logger.error(`执行内部任务失败: ${req.body.taskType}`, { error: error.message });
    res.status(500).json({
      success: false,
      error: '执行内部任务失败',
      message: error.message
    });
  }
});

/**
 * @route GET /api/internal/stats/system
 * @desc 获取系统统计信息
 * @access Private
 */
router.get('/stats/system', async (req, res) => {
  try {
    logger.info('获取系统统计信息');
    
    const stats = internalService.getSystemStats();
    
    res.json({
      success: true,
      data: stats,
      timestamp: new Date().toISOString()
    });
  } catch (error) {
    logger.error('获取系统统计信息失败', { error: error.message });
    res.status(500).json({
      success: false,
      error: '获取系统统计信息失败',
      message: error.message
    });
  }
});

/**
 * @route POST /api/internal/maintenance/start
 * @desc 开始系统维护
 * @access Private
 */
router.post('/maintenance/start', validateRequest({
  type: 'string|required',
  duration: 'number|optional',
  description: 'string|optional'
}), async (req, res) => {
  try {
    const { type, duration, description } = req.body;
    
    logger.info(`开始系统维护: ${type}`, { duration, description });
    
    const result = await internalService.executeTask('maintenance', {
      type,
      duration,
      description
    });
    
    res.json({
      success: true,
      data: result,
      message: '系统维护已开始',
      timestamp: new Date().toISOString()
    });
  } catch (error) {
    logger.error('开始系统维护失败', { error: error.message });
    res.status(500).json({
      success: false,
      error: '开始系统维护失败',
      message: error.message
    });
  }
});

/**
 * @route POST /api/internal/cache/refresh
 * @desc 刷新系统缓存
 * @access Private
 */
router.post('/cache/refresh', validateRequest({
  keys: 'array|optional',
  force: 'boolean|optional'
}), async (req, res) => {
  try {
    const { keys, force = false } = req.body;
    
    logger.info('刷新系统缓存', { keys, force });
    
    const result = await internalService.executeTask('cacheRefresh', {
      keys,
      force
    });
    
    res.json({
      success: true,
      data: result,
      message: '缓存刷新完成',
      timestamp: new Date().toISOString()
    });
  } catch (error) {
    logger.error('刷新系统缓存失败', { error: error.message });
    res.status(500).json({
      success: false,
      error: '刷新系统缓存失败',
      message: error.message
    });
  }
});

/**
 * @route POST /api/internal/data/sync
 * @desc 同步数据
 * @access Private
 */
router.post('/data/sync', validateRequest({
  tables: 'array|optional',
  incremental: 'boolean|optional',
  cycleTime: 'string|optional'
}), async (req, res) => {
  try {
    const { tables, incremental = true, cycleTime } = req.body;
    
    // 如果没有传入cycleTime，自动生成当前时间
    const finalCycleTime = cycleTime || new Date().toLocaleString('zh-CN', {
      timeZone: 'Asia/Shanghai',
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit',
      hour12: false
    }).replace(/\//g, '-');
    
    logger.info('开始数据同步', { tables, incremental, cycleTime: finalCycleTime });
    
    const result = await internalService.executeTask('dataSync', {
      tables,
      incremental,
      cycleTime: finalCycleTime
    });
    
    res.json({
      success: true,
      data: result,
      message: '数据同步完成',
      timestamp: new Date().toISOString()
    });
  } catch (error) {
    logger.error('数据同步失败', { error: error.message });
    res.status(500).json({
      success: false,
      error: '数据同步失败',
      message: error.message
    });
  }
});

/**
 * @route GET /api/internal/health/detailed
 * @desc 获取详细健康检查信息
 * @access Private
 */
router.get('/health/detailed', async (req, res) => {
  try {
    logger.info('执行详细健康检查');
    
    const healthStatus = await internalService.executeTask('healthCheck', {
      detailed: true,
      includeMetrics: true
    });
    
    res.json({
      success: true,
      data: healthStatus,
      timestamp: new Date().toISOString()
    });
  } catch (error) {
    logger.error('详细健康检查失败', { error: error.message });
    res.status(500).json({
      success: false,
      error: '详细健康检查失败',
      message: error.message
    });
  }
});

module.exports = router;
